<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>物料管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <style>
        .selected-box {
            background-color: #e6f7ff;
            border: 1px solid #91d5ff;
            padding: 10px 15px;
            margin-bottom: 15px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <!-- 搜索表单 -->
        <div style="margin: 30px 10px 20px 10px">
            <form class="layui-form layui-form-pane" action="">
                <div class="layui-form-item" style="display: flex; align-items: center; flex-wrap: wrap;">
                    <div class="layui-inline" style="margin-bottom: 0; display: flex; align-items: center; margin-right: 10px;">
                        <label class="layui-form-label" style="width:auto; padding:0 15px; border:none; background:transparent; height:36px; line-height:36px;">物料编号</label>
                        <div class="layui-input-inline" style="width:140px;">
                            <input type="text" name="materialCode" class="layui-input" placeholder="请输入物料编号" style="border-radius:4px;">
                        </div>
                    </div>
                    <div class="layui-inline" style="margin-bottom: 0; display: flex; align-items: center; margin-right: 10px;">
                        <label class="layui-form-label" style="width:auto; padding:0 15px; border:none; background:transparent; height:36px; line-height:36px;">物料名称</label>
                        <div class="layui-input-inline" style="width:140px;">
                            <input type="text" name="materialName" class="layui-input" placeholder="请输入物料名称" style="border-radius:4px;">
                        </div>
                    </div>

                    <div class="layui-inline" style="margin-bottom: 0; display: flex; align-items: center; margin-right: 10px;">
                        <label class="layui-form-label" style="width:auto; padding:0 15px; border:none; background:transparent; height:36px; line-height:36px;">供应商ID</label>
                        <div class="layui-input-inline" style="width:140px;">
                            <input type="text" name="supplierId" class="layui-input" placeholder="请输入供应商ID" style="border-radius:4px;">
                        </div>
                    </div>

                    <div class="layui-inline" style="margin-bottom: 0; display: flex; align-items: center;">
                        <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit lay-filter="data-search-btn" style="border-radius:4px; margin-right:5px;">
                            <i class="layui-icon">&#xe615;</i>查询
                        </button>
                        <button type="reset" class="layui-btn layui-btn-normal layui-btn-sm" style="border-radius:4px; margin-right:5px;">
                            <i class="layui-icon">&#xe669;</i>重置
                        </button>
                        <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="add" style="border-radius:4px; margin-right:5px;">
                            <i class="layui-icon">&#xe654;</i>新增物料
                        </button>
                        <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="import" style="border-radius:4px;">
                            <i class="layui-icon">&#xe67c;</i>物料导入
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 批量操作区域 -->
        <div class="selected-box" style="margin: 0 10px 15px 10px; display: flex; align-items: center;">
            <span id="selected-count" style="margin-left: 10px;">已选择0项</span>
            <div style="width: 20px;"></div>
            <button class="layui-btn layui-btn-sm" id="batch-delete-btn" style="background-color: transparent; color: #1E9FFF; font-weight: bold; font-size: 14px;">清空</button>
            <div style="width: 10px;"></div>
            <button class="layui-btn layui-btn-sm" id="clear-selection-btn" style="background-color: transparent; color: #FF5722; font-weight: bold; font-size: 14px;">清空选择</button>
        </div>

        <!-- 表格容器 -->
        <div style="margin: 0 10px">
            <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        </div>

        <!-- 表格操作按钮模板 -->
        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

        <!-- 编辑/添加弹窗 -->
        <div id="edit" style="display: none">
            <div class="layui-form layuimini-form" lay-filter="editForm">
                <div class="layui-form-item" id="materialId-laylabel">
                    <label class="layui-form-label required">物料ID</label>
                    <div class="layui-input-inline">
                        <input type="text" name="materialId" placeholder="物料ID" readonly value="" class="layui-input layui-disabled">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label required">物料编号</label>
                    <div class="layui-input-inline">
                        <input type="text" name="materialCode" lay-verify="required" lay-reqtext="物料编号不能为空" placeholder="请输入物料编号" value="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label required">物料名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="materialName" lay-verify="required" lay-reqtext="物料名称不能为空" placeholder="请输入物料名称" value="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">物料简称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="materialShortName" placeholder="请输入物料简称" value="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label required">物料类型</label>
                    <div class="layui-input-inline">
                        <select name="materialType" lay-verify="required">
                            <option value="">请选择物料类型</option>
                            <option value="1">普通物料</option>
                            <option value="2">电缆</option>
                            <option value="3">导线</option>
                            <option value="4">变电器材</option>
                            <option value="5">新品</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">供应商ID</label>
                    <div class="layui-input-inline">
                        <input type="text" name="supplierId" placeholder="请输入供应商ID" value="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label required">计量单位</label>
                    <div class="layui-input-inline">
                        <input type="text" name="materialUnit" lay-verify="required" placeholder="请输入计量单位" value="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">规格</label>
                    <div class="layui-input-inline">
                        <input type="text" name="materialSpec" placeholder="请输入规格" value="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">型号</label>
                    <div class="layui-input-inline">
                        <input type="text" name="materialModel" placeholder="请输入型号" value="" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'layer', 'upload'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            layer = layui.layer,
            upload = layui.upload;

        var index;
        var selectedIds = [];

        // 表格渲染
        table.render({
            elem: '#currentTableId',
            url: '/material/queryPage',
            parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.data.total,
                    "data": res.data.list
                };
            },
            // 移除了toolbar配置，因为按钮不在工具栏中
            //toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'materialId', width: 100, title: '物料ID', sort: true},
                {field: 'materialCode', width: 150, title: '物料编号'},
                {field: 'materialName', width: 150, title: '物料名称'},
                {field: 'materialShortName', width: 150, title: '物料简称'},
                {field: 'materialUnit', width: 100, title: '计量单位'},
                {field: 'supplierId', width: 100, title: '供应商ID'},
                {field: 'materialCreateTime', width: 180, title: '创建时间'},
                {field: 'materialUpdateTime', width: 180, title: '更新时间'},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [5, 10, 50, 100],
            limit: 10,
            page: true,
            skin: 'line',
            done: function(res, curr, count) {
                // 每次表格重新渲染后清空选择
                selectedIds = [];
                updateSelectedCount();
            }
        });




        // 复选框选择监听
        table.on('checkbox(currentTableFilter)', function(obj){
            var data = obj.data;
            if(obj.checked){
                if(obj.type === 'all') {
                    // 全选
                    selectedIds = [];
                    var checkStatus = table.checkStatus('currentTableId');
                    layui.each(checkStatus.data, function(index, item) {
                        selectedIds.push(item.materialId);
                    });
                } else {
                    // 单选
                    if(selectedIds.indexOf(data.materialId) === -1) {
                        selectedIds.push(data.materialId);
                    }
                }
            } else {
                if(obj.type === 'all') {
                    // 取消全选
                    selectedIds = [];
                } else {
                    // 取消单选
                    selectedIds = selectedIds.filter(function(id){
                        return id !== data.materialId;
                    });
                }
            }
            updateSelectedCount();
        });


        // 更新已选择数量显示
        function updateSelectedCount() {
            $('#selected-count').text('已选择' + selectedIds.length + '项');
        }

        // 批量删除按钮点击事件
        $('#batch-delete-btn').click(function(){
            if(selectedIds.length === 0) {
                layer.msg('请至少选择一项', {icon: 2});
                return;
            }

            layer.confirm('确定删除选中的' + selectedIds.length + '项数据吗？', function(index){
                $.post('/material/deleteBatch', {ids: selectedIds.join(',')}, function(res){
                    if(res.code === 0) {
                        layer.msg('删除成功');
                        table.reload('currentTableId');
                    } else {
                        layer.msg('删除失败');
                    }
                });
                layer.close(index);
            });
        });

        // 清空选择按钮点击事件
        $('#clear-selection-btn').click(function(){
            selectedIds = [];
            updateSelectedCount();
            // 取消表格中的所有选择
            var checkStatus = table.checkStatus('currentTableId');
            if(checkStatus.data.length > 0) {
                $('.layui-table-header th[data-field="LAY_CHECKED"] input[type="checkbox"]').prop('checked', false);
                $('.layui-table-body tbody tr td[data-field="LAY_CHECKED"] input[type="checkbox"]').prop('checked', false);
                table.reload('currentTableId');
            }
        });


        // 搜索监听
        form.on('submit(data-search-btn)', function (data) {
            table.reload('currentTableId', {
                page: {curr: 1},
                where: data.field
            }, 'data');
            return false;
        });


        // 新增物料功能
        function addMaterial() {
            // 先关闭可能已经存在的弹窗
            if(index) {
                layer.close(index);
            }
            $("#materialId-laylabel").hide();
            form.val("editForm", {
                materialId: '',
                materialCode: '',
                materialName: '',
                materialShortName: '',
                materialSpecification: '',
                materialSupplier: '',
                materialUnit: '',
                materialVolume: ''
            });
            index = layer.open({
                title: '添加物料',
                type: 1,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['40%', '70%'],
                content: $("#edit"),
                cancel: function() {
                    // 弹窗关闭时清空index变量
                    index = null;
                }
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        }

        // 物料导入功能
        function importMaterial() {
            // 先关闭可能已经存在的弹窗
            if(index) {
                layer.close(index);
            }
            index = layer.open({
                title: '物料导入',
                type: 1,
                area: ['500px', '300px'],
                content: '<div style="padding: 20px;"><div class="layui-upload-drag" id="uploadExcel">' +
                    '<i class="layui-icon"></i>' +
                    '<p>点击上传，或将文件拖拽到此处</p>' +
                    '<p>支持格式：xls、xlsx</p>' +
                    '</div></div>',
                cancel: function() {
                    // 弹窗关闭时清空index变量
                    index = null;
                },
                success: function(layero, index){
                    upload.render({
                        elem: '#uploadExcel',
                        url: '/material/importExcel',
                        accept: 'file',
                        exts: 'xls|xlsx',
                        done: function(res){
                            if(res.code === 0) {
                                layer.msg('导入成功');
                                table.reload('currentTableId');
                                layer.close(index);
                            } else {
                                layer.msg(res.msg || '导入失败');
                            }
                        },
                        error: function(){
                            layer.msg('上传失败');
                        }
                    });
                }
            });
        }


        // 使用form.on来监听按钮点击，因为按钮在表单内
        form.on('submit(data-search-btn)', function (data) {
            table.reload('currentTableId', {
                page: {curr: 1},
                where: data.field
            }, 'data');
            return false;
        });


        // 直接绑定按钮点击事件 - 这是最可靠的方式
        $(document).on('click', 'button[lay-event="add"]', function(e) {
            e.preventDefault();
            e.stopPropagation();
            addMaterial();
            return false;
        });

        $(document).on('click', 'button[lay-event="import"]', function(e) {
            e.preventDefault();
            e.stopPropagation();
            importMaterial();
            return false;
        });




        // 行内按钮监听 - 编辑 & 删除
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                $("#materialId-laylabel").show();
                form.val("editForm", data);
                index = layer.open({
                    title: '编辑物料',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['40%', '70%'],
                    content: $("#edit")
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('确定删除该物料？', function (index) {
                    $.getJSON("/material/delete?id=" + data.materialId, function (res) {
                        if (res.code === 0) {
                            layer.msg("删除成功");
                            obj.del();
                        } else {
                            layer.msg("删除失败");
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 表单提交监听
        form.on('submit(saveBtn)', function (data) {
            var field = data.field;
            // 设置当前时间
            var now = new Date();
            field.materialCreateTime = now;
            field.materialUpdateTime = now;
            // 确保materialType是数字
            if(field.materialType) {
                field.materialType = parseInt(field.materialType);
            }

            var url = field.materialId ? "/material/update" : "/material/add";
            // $.post(url, field, function (res) {
            //     if (res.code === 0) {
            //         layer.msg(field.materialId ? "更新成功" : "添加成功");
            //         table.reload('currentTableId');
            //         layer.close(index);
            //     } else {
            //         layer.msg(field.materialId ? "更新失败" : "添加失败");
            //     }
            // });
            $.ajax({
                url: url,
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(field),
                success: function(res) {
                    if (res.code === 0) {
                        layer.msg(field.materialId ? "更新成功" : "添加成功");
                        table.reload('currentTableId');
                        layer.close(index);
                    } else {
                        layer.msg(res.msg || (field.materialId ? "更新失败" : "添加失败"));
                    }
                },
                error: function() {
                    layer.msg("请求失败，请检查网络");
                }
            });
            return false;
        });
    });
</script>
</body>
</html>